package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Ksda;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Yfd;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdzzj;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdzzjMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMdzzjParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMdzzjResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyMdzzjService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-12-22
 */
@Service
public class BtyMdzzjServiceImpl extends ServiceImpl<BtyMdzzjMapper, BtyMdzzj> implements BtyMdzzjService {

    @Override
    public void add(BtyMdzzjParam param){
        BtyMdzzj entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyMdzzjParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyMdzzjParam param){
        BtyMdzzj oldEntity = getOldEntity(param);
        BtyMdzzj newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyMdzzjResult findBySpec(BtyMdzzjParam param){
        return null;
    }

    @Override
    public List<BtyMdzzjResult> findListBySpec(BtyMdzzjParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyMdzzjParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 导入excel
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchImport(String fileName, MultipartFile file, BtyMdzzjParam param){
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            //导入之前删掉之前的数据
            baseMapper.delete(new QueryWrapper<>());

            //int sheets = wb.getNumberOfSheets();
            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
//                    Cell cell1 = row.getCell(0);
//                    if (ToolUtil.isNotEmpty(cell1)) {
//                        cell1.setCellType(CellType.STRING);
//                    }

                    Cell cell3 = row.getCell(1);
                    if (ToolUtil.isNotEmpty(cell3)) {
                        cell3.setCellType(CellType.STRING);
                    }

                    Cell cell0 = row.getCell(2);
                    if (ToolUtil.isNotEmpty(cell0)) {
                        cell0.setCellType(CellType.STRING);
                    }

                    Cell cell2 = row.getCell(3);
                    if (ToolUtil.isNotEmpty(cell2)) {
                        cell2.setCellType(CellType.STRING);
                    }

                    //店名
                    Date zdrqs=row.getCell(0).getDateCellValue();
                    String zdrq= DateUtil.getStrDate(zdrqs);
                    //String zdrq=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    String dm=row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //金额
                    String je = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //卡号
                    String kh = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
                    BtyMdzzj mdzzj=new BtyMdzzj();
                    mdzzj.setDm(dm.replaceAll("\\s*", ""));
                    mdzzj.setJe(new BigDecimal(je).setScale(2, BigDecimal.ROUND_HALF_UP));
                    mdzzj.setYhk(kh);
                    mdzzj.setZdrq(zdrq);
                    baseMapper.insert(mdzzj);
                }
            }
            //导入成功之后按大区生成凭证
            //String zdrq=param.getZdrq();
            //String zdrq="2021-11-23";
            String bh="201";
            List<BtyMdzzjResult> list=baseMapper.zzjList();
            for (BtyMdzzjResult mxResult : list) {
                BigDecimal je = mxResult.getJe();
                String ksbm ="";
                String dm = mxResult.getDm();
                String zdrq=mxResult.getZdrq();
                String yhk=mxResult.getYhk();
                //根据店名查询客商辅助核算编码
                String json = "{\"custname\":\""+dm+"\"}";
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                HttpEntity<String> formEntitys = new HttpEntity<String>(json, headers);
                String urls = "http://124.70.28.147:8089/u8cloud/api/uapbd/custdoc/query";

                Yfd yfd = restTemplate.postForEntity(urls, formEntitys, Yfd.class).getBody();
                JSONObject resultObject = JSON.parseObject(yfd.getData());
                JSONArray jsonArray = resultObject.getJSONArray("datas");
                JSONObject jsonObject;
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        jsonObject = jsonArray.getJSONObject(0);
                        Ksda.DatasBean.ParentvoBean parentvo = jsonObject.getObject("parentvo", Ksda.DatasBean.ParentvoBean.class);
                        ksbm=parentvo.getCustcode();
                    }
                }

                StringBuilder sb=new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");

                sb.append("                {\n" +
                        "                    \"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"96\",\n" +
                        "                            \"checkvaluecode\":"+yhk+"\n" +//银行账户辅助核算
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"\",\n" +
                        "                    \"debitamount\":\""+je+"\",\n" +
                        "                    \"explanation\":\"备用金\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"100203\",\n" +
                        "                    \"pk_currtype\":\"CNY\"\n" +
                        "                }," +
                        "{\n" +
                        "\t\t\t\t\"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"73\",\n" +
                        "                            \"checkvaluecode\":'"+ksbm+"'\n" +//客商辅助核算编码
                        "                        },\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\""+je+"\",\n" +
                        "                    \"creditquantity\":\"\",\n" +
                        "                    \"debitamount\":\"\",\n" +
                        "                    \"debitquantity\":\"\",\n" +
                        "                    \"detailindex\":\"\",\n" +
                        "                    \"excrate1\":\"\",\n" +
                        "                    \"explanation\":\"备用金\",\n" +
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"224101\",\n" +
                        "                    \"pk_currtype\":\"CNY\",\n" +
                        "                    \"price\":\"\"\n" +
                        "                },\n");
                sb.append("            ],\n" +
                        "            \"pk_corp\":"+bh+",\n" +
                        "            \"pk_glorgbook\":\""+bh+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");

                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if (status.equals("falied")) {
                    String errormsg = jo.get("errormsg").getAsString();
                    BtyMdzzj shdkmx=baseMapper.selectOne(new QueryWrapper<BtyMdzzj>().eq("dm",dm).eq("yhk",yhk));
                    if(ToolUtil.isNotEmpty(shdkmx)){
                        shdkmx.setErrormsg(errormsg);
                        baseMapper.updateById(shdkmx);
                    }
                    System.out.println("errormsg:"+errormsg);
                } else {
                    BtyMdzzj shdkmx=baseMapper.selectOne(new QueryWrapper<BtyMdzzj>().eq("dm",dm).eq("yhk",yhk));
                    if(ToolUtil.isNotEmpty(shdkmx)){
                        shdkmx.setFlag(1);
                        baseMapper.updateById(shdkmx);
                    }
                }
            }

        } catch (Exception e) {
            notNull=false;
            e.printStackTrace();
        }
        return notNull;
    }

    private Serializable getKey(BtyMdzzjParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyMdzzj getOldEntity(BtyMdzzjParam param) {
        return this.getById(getKey(param));
    }

    private BtyMdzzj getEntity(BtyMdzzjParam param) {
        BtyMdzzj entity = new BtyMdzzj();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
